package jwtRequest

import (
	"github.com/dgrijalva/jwt-go"
	"time"
	"week_one/client/common/global"
)

type Jwt struct {
	SigningKey []byte
}
type JwtClient interface {
	CreateToken(id uint, name string) (string, error)
	ParseToken(tokenString string) *ClaimsToken
}

func NewJwtClient(signingKey []byte) JwtClient {
	return &Jwt{SigningKey: signingKey}
}
func (j *Jwt) CreateToken(id uint, name string) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = &ClaimsToken{
		Id:   id,
		Name: name,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + global.ClientConfig.JwtConf.ExpiresAt,
		},
	}
	return token.SignedString(j.SigningKey)
}
func (j *Jwt) ParseToken(tokenString string) *ClaimsToken {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(global.ClientConfig.JwtConf.SigningKey), nil
	})
	if err != nil {
		panic(err)
	}
	claims := token.Claims.(jwt.MapClaims)
	return &ClaimsToken{
		Id:   uint(claims["Id"].(float64)),
		Name: claims["Name"].(string),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: int64(claims["exp"].(float64)),
		},
	}
}
